<template>
  <div>
    <div>
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item>
          <el-button type="primary" @click="onSubmit">添加角色</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-table :data="roleList" border style="width: 100%">
      <el-table-column
        header-align="center"
        align="center"
        prop="num"
        label="id"
        width="180"
      />
      <el-table-column
        header-align="center"
        align="center"
        prop="name"
        label="名字"
        width="180"
      />
      <el-table-column
        header-align="center"
        align="center"
        prop="edit"
        label="操作"
      >
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)"
            >修改权限</el-button
          >
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import { defineComponent, onMounted, reactive, toRefs } from 'vue'
import { useRouter } from 'vue-router'
import { getRoleList } from '../request/api'
import { roleData, roleInt } from '../type/role'
export default defineComponent({
  setup() {
    onMounted(() => {
      getRole()
    })

    const router = useRouter()

    const data = reactive(new roleData())

    const getRole = () => {
      getRoleList()
        .then((res) => {
          data.roleList = res.data
        })
        .catch((err) => {
          console.log(err)
        })
    }

    const onSubmit = () => {
      ElMessageBox.prompt('请输入角色名称', '添加角色', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })
        .then(({ value }) => {
          if (value) {
            //此处是手动修改界面数据
            data.roleList.push({ num: data.roleList.length + 1, name: value })
          }
          ElMessage({
            type: 'success',
            message: `${value}角色添加成功`
          })
        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: '取消操作'
          })
        })
    }

    const handleEdit = (row: roleInt) => {
      router.push({
        name: 'authority',
        params: {
          num: row.num,
          name: row.name
        }
      })
    }

    return { ...toRefs(data), onSubmit, handleEdit }
  }
})
</script>

<style scoped></style>
